package com.item.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.item.pojo.Admin;
import com.item.pojo.User;
import com.item.service.AdminService;
import com.item.service.UserService;
import com.item.utils.Constants;
import com.item.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private AdminService loginService;


    @GetMapping
    public List<User> getPages(){
        return userService.selectAll();
    }

    @GetMapping("/{id}")
    public User selectById(@PathVariable Integer id){
        return userService.selectById(id);
    }


    @PostMapping
    public int update(@RequestBody User user){
        int update = userService.update(user);
        return update;
    }

    @PutMapping
    public int insert(@RequestBody User user){
        if (user.getPassword()==null) {
            user.setPassword("123");
        }
        int insert = userService.insert(user);
        return insert;

    }

    //根据id删除
    @DeleteMapping("/{id}")
    public int delete(@PathVariable Integer id){
        int delete = userService.delete(id);
        return delete;
    }


    //批量删除
    @PostMapping("/del/batch")
    public int delBatch(@RequestBody List<Integer> ids){
        return userService.delBatch(ids);
    }


    @GetMapping("/pageList")
    public Map<String,Object> pageList(@RequestParam Integer page, @RequestParam Integer pageSize,User user){
        Map<String,Object> map =  userService.pageList(pageSize,page,user);
        return map;
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.selectAll();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
//        writer.addHeaderAlias("username", "用户名");
//        writer.addHeaderAlias("password", "密码");
//        writer.addHeaderAlias("nickname", "昵称");
//        writer.addHeaderAlias("email", "邮箱");
//        writer.addHeaderAlias("phone", "电话");
//        writer.addHeaderAlias("address", "地址");
//        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //List<User> list = reader.readAll(User.class);
        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(1).toString());
            user.setPassword(row.get(2).toString());
            user.setNickname(row.get(3).toString());
            user.setEmail(row.get(4).toString());
            user.setPhone(row.get(5).toString());
            user.setAddress(row.get(6).toString());
            user.setImgUrl(row.get(7).toString());
            users.add(user);
        }

        userService.insertBatch(users);
        return true;
    }


    //登录
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        String username = admin.getAdminName();
        String password = admin.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }
        Admin admin1 = loginService.login(admin);
        return Result.success(admin1);
    }


}
